package cn.datawin.service;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;





import org.bson.types.ObjectId;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import cn.datawin.bean.Form;
import cn.datawin.bean.RuleBase;
import cn.datawin.bean.page.ReqData;
import cn.datawin.bean.page.RespData;
import cn.datawin.spider.seletor.Html;
import cn.datawin.util.HtmlImg;
import cn.datawin.util.SpiderUtil;

import com.alibaba.fastjson.JSON;
import com.googlecode.jsonplugin.JSONException;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;


@Service
public class RuleBaseService extends BaseService{
	
	public void insertRuleBase(RuleBase ruleBase) {
		String col="rulebase";
//		if (map.get("expression")!=null && !map.get("expression").equals("")) {
//			map.put("expression", JSON.parseArray(map.get("expression").toString(), LinkedHashMap.class));
//		}
		this.insertAsBean(col, ruleBase);
	}
	
	
	public void deleteRule(String id){
		String col="rule";
		Map<String, Object> query = new HashMap<String, Object>();
		query.put("_id", new ObjectId(id));
		this.delete(col, query);
	}
	
	public Object getRuleBase(Form form,ReqData reqData) throws JSONException {
		BasicDBObject query = new BasicDBObject();
		RespData<List<DBObject>> res=makeRes(form, reqData);
		return res;
	}

	public RespData<List<DBObject>> makeRes(Form form,ReqData reqData){
		RespData<List<DBObject>> respData = new RespData<List<DBObject>>();
		//获取条件
		BasicDBObject query = new BasicDBObject();
		
		if(StringUtils.hasLength(form.getKey())){
			Pattern pattern = Pattern.compile("^.*" + form.getKey()+ ".*$", Pattern.CASE_INSENSITIVE);
			BasicDBObject q1 = new BasicDBObject();
			q1.append("rulename", pattern);
			BasicDBObject q2 = new BasicDBObject();
			q2.append("belone", pattern);
			BasicDBList values = new BasicDBList();
			values.add(q1);values.add(q2);
			query.append("$or",values);
		}
		int start = (reqData.getPage() - 1) * reqData.getRows();
		BasicDBObject sort = null;
		//设置sort
		if(reqData.getSort()!=null){
			sort = new BasicDBObject(reqData.getSort(), sortmap.get(reqData.getOrder())); 
		}
		long count=super.count("rulebase", query);
		List<DBObject> rows = super.findList("rulebase", query, sort, start, reqData.getRows());
		for (int i = 0; i < rows.size(); i++) {
			if (rows.get(i).get("expression") != null && !rows.get(i).get("expression").equals("")) {
				rows.get(i).put("expression", rows.get(i).get("expression").toString());
			}
		}
		respData.setRows(rows);
		respData.setTotal(count);
		return respData;
	}
	
	public void updateRuleBase(RuleBase ruleBase) {
		String col="rulebase";
		this.updateByidAsBean(col, ruleBase.get_id(), ruleBase);
	}
	
	public void deleteRuleBase(String id) {
		String col="rulebase";
		BasicDBObject query = new BasicDBObject();
		query.put("_id", new ObjectId(id));
		this.delete(col, query);
	}
	
	public DBObject findRuleBase(String id) {
		String col="rulebase";
		BasicDBObject query = new BasicDBObject();
		query.put("_id", new ObjectId(id));
		return this.findOne(col, query);
	}
	
	public HashMap<String, Object> ruleTest(List<? extends Map > expressions,String reshtml,String url){
		HashMap<String, Object> params = new HashMap<String, Object>();
		for (Map<String, String> map : expressions) {
			Html html = new Html(reshtml);
			HtmlImg Imghtml = new HtmlImg(html.toString());
			if(Boolean.valueOf(map.remove("execjs"))){  // 用于执行 js 的判断
				Imghtml.execjs();
			}else{
				Imghtml.setElements(html.getElements());
			}
			Imghtml.setUrl(url);
			
			Set<String> sets = map.keySet();
			String n=map.remove("name");
			Iterator<String> ite = sets.iterator();
			while (ite.hasNext()) {
				String type = ite.next();
				String value = map.get(type);
				Method me = SpiderUtil.getHtmlMethod(type);
				Object result = null;
				if(!StringUtils.hasLength(value)){
					result = SpiderUtil.invokeMethod(me, Imghtml);
				}else{
					result = SpiderUtil.invokeMethod(me, Imghtml, value);
				}
				if (!ite.hasNext()) {
					if(result == null || result.toString().isEmpty()){
						continue;
					}
					params.put(n, result.toString());
				}
			}
			map.put("name", n);
		}
		return params;
	}
	
	
	public HashMap<String, List<String>> paramsSplit(List<? extends Map> expressions,DBObject rule,HashMap<String, Object> params){
		HashMap<String, List<String>> dataparams = new HashMap<String, List<String>>();
		List<String> nameList = new ArrayList<String>();	//用来存放返回的name
		for (int j = 0; j < expressions.size(); j++) {
			String name = expressions.get(j).get("name").toString();
			nameList.add(name);
			String data = (String)params.get(name);
			System.out.println(name +"======="+data);
			if(data == null) {
				data ="";
			}
			String datas[] = data.split("\\^\\|");
			List<String> dataparam = new ArrayList<String>();
			for (int k = 0; k < datas.length; k++) {
				dataparam.add(datas[k]);
			}
			dataparams.put(name, dataparam);
		}
		dataparams.put("nameList", nameList);
		
		return dataparams;
	}
	
	public HashMap<String, List<String>> nexturl(DBObject rule,List<? extends Map> expressions,HashMap<String, Object> params){
		HashMap<String, List<String>> nextlists = new HashMap<String, List<String>>();
		List<String> nameList = new ArrayList<String>();	//用来存放返回的name
		List<String> nextlist = new ArrayList<String>();
		if (rule.get("type").toString().equals("PageProcessor")) {
			int pn = 1;
			if (rule.get("pageNum").toString() != null && !rule.get("pageNum").toString().equals("")) {
				pn=Integer.parseInt(rule.get("pageNum").toString());
			}
			if(pn==1){
				for (int i = 1; i <= Integer.parseInt(rule.get("pageSize").toString()); i++) {
					String pageRule = rule.get("pageRule").toString();
					for (int j = 0; j < expressions.size(); j++) {
						String url = (String) params.get(expressions.get(j).get("name"));
						String replace =  pageRule.replace("\\d", i + "");
						String nextUrl = url.replaceAll(pageRule, replace);
						if (!nextlist.contains(nextUrl)) {
							nextlist.add(nextUrl);
						}
					}
				}
			}else if(pn>=100){
				for (int i = 0; i < Integer.parseInt(rule.get("pageSize").toString()); i++) {
					String pageRule = rule.get("pageRule").toString();
					for (int j = 0; j < expressions.size(); j++) {
						String url = (String) params.get(expressions.get(j).get("name"));
						String replace =  pageRule.replace("\\d\\d\\d", i*pn + "");
						String nextUrl = url.replaceAll(pageRule, replace);
						if (!nextlist.contains(nextUrl)) {
							nextlist.add(nextUrl);
						}
					}
				}
			}else{
				for (int i = 0; i < Integer.parseInt(rule.get("pageSize").toString()); i++) {
					String pageRule = rule.get("pageRule").toString();
					for (int j = 0; j < expressions.size(); j++) {
						String url = (String) params.get(expressions.get(j).get("name"));
						String replace =  pageRule.replace("\\d\\d", i*pn+ "");
						String nextUrl = url.replaceAll(pageRule, replace);
						if (!nextlist.contains(nextUrl)) {
							nextlist.add(nextUrl);
						}
					}
				}
				
			}
		}
		
		for (Map<String, String> map : expressions) {
			nameList.add(map.get("name"));
			nextlists.put(map.get("name"), nextlist);
		}
		nextlists.put("nameList", nameList);
		return nextlists;
	}


	public HashMap<String, List<String>> urlRule(DBObject rule, List<LinkedHashMap> expressions, HashMap<String, Object> params) {
		HashMap<String, List<String>> map = new HashMap<String, List<String>>();
		List<String> nameList = new ArrayList<String>();
		nameList.add("typeUrl");
//		List<String[]> datamap=new ArrayList<String[]>();
		String urlRule = (String) rule.get("urlRule");
		List<String> list = new ArrayList<String>();
		String url=urlRule;
		int i=0;
		for (int j = 0; j < expressions.size(); j++) {
			String name = expressions.get(j).get("name").toString();
			String data = params.get(name).toString();
			String []tmp =data.split("\\^\\|");
			List<String> list_tmp = new ArrayList<String>();
			if(i>0){
				list_tmp.addAll(list);
				list.clear();	
			}
			
			for(String tt :tmp){
				if(i>0){
					for(String ttt: list_tmp){
						list.add(ttt.replaceFirst("%s",tt ));
					}
					continue;
				}
				list.add(url.length()>0 ? url.replaceFirst("%s",tt ): tt) ;
			}
			i++;
			
		}
		map.put("typeUrl", list  );
		
		map.put("nameList", nameList);
		return map;
	}
	
	public static void main(String[] args) {
		    
//		Pattern regex = Pattern.compile(regexStr, Pattern.DOTALL
//				| Pattern.CASE_INSENSITIVE);
//		Matcher matcher = regex.matcher(elements.toString());
//		boolean find = matcher.find();
	}
	
}
